package com.mengrv.springbootdemo.model;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import io.swagger.annotations.ApiModel;

import java.util.List;

@ApiModel(description = "接口返回数据模板")
public class Response<T> {
    private String statusText = "接口请求成功";
    private int statusCode = 200;
    private JSONObject content = null;
    // private T content;

    public void setAll(T content, String statusText, int statusCode) {
        setContent(content);
        setStatusText(statusText);
        setStatusCode(statusCode);
    }

    public void setContent(T content) {
        // this.content = content;

        //为null的值不返回，参数按照字母表顺序返回
        if (content instanceof List) { //ArrayList进行排序
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("list", content);
            jsonObject.put("length", ((List) content).size());
            this.content = JSON.parseObject(jsonObject.toJSONString(), Feature.OrderedField);
        } else if (content instanceof Object) { //Object进行排序
            String jsonString = JSONObject.toJSONString(content);
            this.content = JSON.parseObject(jsonString, Feature.OrderedField);
        }
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public void setStatusText(String statusText) {
        this.statusText = statusText;
    }

    public int getStatusCode() {
        return statusCode;
    }

    public String getStatusText() {
        return statusText;
    }

    public void setError(String statusText) {
        this.statusText = statusText != null ? statusText : "接口请求失败";
        this.statusCode = 0;
    }

    public JSONObject getContent() {
        return content;
    }
}
